<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

/**
 * 在线抽奖活动点击量统计表
 */
class TurnActivityBrowseCount extends BaseModel
{
    use HasFactory;


    const CREATED_AT = 'create_time';
    const UPDATED_AT = null;


    protected $table = 'turn_activity_browse_count';


    /**
     * 添加活动统计数据
     * 
     * @param act_id 活动id  
    // * @param unit_id 单位id  空表示全部  0 表示全部
     * @param number 多少次更新一次
     * @param second 大于秒更新一次（取决于后一次请求事件）
     */
    public function updateBrowseNumber($act_id, $number = 100, $second = 300)
    {
        if(empty($act_id)){
            return false;
        }
        if ($number == 1) {
            return $this->change($act_id);
        }

        $key = $act_id . '_turn_activity_total_browse_number';
        $res = Cache::pull($key); //从缓存中获取缓存项然后删除，使用 pull 方法，如果缓存项不存在的话返回 null
        $data = [];
        if (empty($res)) {
            $data['number'] = 1;
            $data['create_time'] = time();
            Cache::put($key, $data, 3600 * 24);
        } else {
            //数据大于50或者时间超过5分钟，则更新一次数据
            if ($res['number'] >= $number || time() - $res['create_time'] >= $second) {
                return $this->change($act_id, $res['number'] + 1);
            } else {
                $data['number'] = $res['number'] + 1;
                $data['create_time'] = $res['create_time'];
                Cache::put($key, $data, 3600 * 24);
            }
        }
        return true;
    }

   
    public function change($act_id, $number = 1,$findWhere = [])
    {
        $res = $this->where('act_id', $act_id)->where('date', date('Y-m-d'))->where('hour', date('H'))->first();
        if ($res) {
            $res->number = $res->number + $number;
            return $res->save();
        }
        $this->act_id = $act_id;
        $this->unit_id = 0;
        $this->date = date('Y-m-d');
        $this->hour = date('H');
        $this->number = $number;

        return  $this->save();
    }

    /**
     * 获取点击量
     * 
     */
    public function getBrowseNumber($act_id, $start_time = null, $end_time = null)
    {
        $res = $this->where(function ($query) use ($act_id,$start_time, $end_time) {
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
            if ($act_id) {
                $query->where('act_id', $act_id);
            }
        })->sum('number');

        return $res;
    }
}
